<template>
    <div>
      <!-- 头部 -->
      <a-card class="headers">
        设备编号：
        <a-input v-model:value="name" placeholder="请输入" style="width: 200px" />
        <a-button type="primary" style="margin-left: 10px" @click="getdata()">
          <template #icon><SearchOutlined /></template>
          查询
        </a-button>
      </a-card>
      <!-- 表格 -->
      <a-card>
        <a-button type="primary" class="but1" @click="showModal">
          <PlusCircleOutlined />
          新建
        </a-button>
        <a-button type="primary" class="but2" @click="putlist">
          批量操作
        </a-button>
        <a-table :columns="columns" :data-source="datas" :pagination="false" :row-selection="rowSelection">
          <template #action="{ record }">
            <a>货道</a>
            <a-divider type="vertical" />
            <a @click="setstra(record)">策略</a>
            <a-divider type="vertical" />
            <a @click="put(record)">修改</a>
          </template>
          <template #state="{ record }">
           <span v-show="record.state==='0'">未投放</span>
           <span v-show="record.state==='1'">运营</span>
           <span v-show="record.state==='2'">撤机</span>
          </template>
        </a-table>
      </a-card>
      <!-- 分页 -->
      <div style="margin-top: 2.5vh; margin-bottom: 4vh" v-if="total > 10">
        <span style="color: #dbe5ef; font-size: 1rem; margin-left: 1rem">
          共{{ total }}条记录&nbsp;&nbsp;第 {{ page }}/{{
            Math.ceil(total / pageSize)
          }}页
        </span>
        <span style="float: right">
          <span style="margin-right: 3vw">
            <a-button
              style="background: #d5ddf8"
              :disabled="page <= 1"
              @click="onup"
              >上一页</a-button
            >
          </span>
          <span style="margin-right: 4vw">
            <a-button
              style="background: #d5ddf8"
              :disabled="page >= Math.ceil(total / pageSize)"
              @click="ondown"
              >下一页</a-button
            >
          </span>
        </span>
      </div>
      <!-- 添加 -->
      <a-modal
        v-model:visible="visible"
        title="新增设备"
        :footer="null"
        @cancel="notOk"
      >
        <a-form
          name="custom-validation"
          ref="formRef"
          :model="formState"
          :rules="rules"
          v-bind="layout"
          @finish="handleFinish"
          @finishFailed="handleFinishFailed"
        >
          <a-form-item label="设备编号">
            系统自动生成
          </a-form-item>
          <a-form-item label="选择型号" name="typeid">
            <a-select v-model:value="formState.typeid" placeholder="请选择">
                <a-select-option v-for="(i) in typedata" :key="i._id" :value="i._id">{{ i.name }}</a-select-option>
            </a-select>
          </a-form-item>
          <a-form-item label="选择点位" name="coding">
            <a-select v-model:value="formState.ptid" placeholder="请选择">
                <a-select-option v-for="(i) in pointslist" :key="i._id" :value="i._id">{{ i.name }}</a-select-option>
            </a-select>
          </a-form-item>
          <a-form-item :wrapper-col="{ span: 17, offset: 7 }">
            <a-button @click="resetForm">取消</a-button>
            <a-button type="primary" html-type="submit" style="margin-left: 50px"
              >确认</a-button
            >
          </a-form-item>
        </a-form>
      </a-modal>
      <!-- 修改 -->
      <a-modal
        v-model:visible="visible2"
        title="策略管理"
        :footer="null"
        @cancel="notOk"
      >
        <a-form
          name="custom-validation"
          ref="formRef"
          :model="formState2"
          :rules="rules"
          v-bind="layout"
          @finish="handleFinish2"
          @finishFailed="handleFinishFailed2"
        >
          <a-form-item label="机器编号">
            {{ formState2._id }}
          </a-form-item>
          <a-form-item label="供货时间">
            {{ formState2.updateTime }}
          </a-form-item>
          <a-form-item label="设备类型">
            {{ formState2.typeid.name }}
          </a-form-item>
          <a-form-item label="设备容量">
            {{ formState2.typeid.capacity }}
          </a-form-item>
          <a-form-item label="设备点位">
            <a-form-item label="选择点位" name="coding">
              <a-select v-model:value="formState2.ptid._id" placeholder="请选择" @change="nono(formState2.ptid._id)">
                  <a-select-option v-for="(i) in pointslist" :key="i._id" :value="i._id">{{ i.name }}</a-select-option>
              </a-select>
            </a-form-item>
          </a-form-item>
          <a-form-item label="合作商">
            {{ formState2.ptid.cooperative.name }}
          </a-form-item>
          <a-form-item label="所属区域">
            {{ formState2.ptid.area.name }}
          </a-form-item>
          <a-form-item label="设备地址">
            {{ formState2.ptid.xidi }}
          </a-form-item>
          <a-form-item :wrapper-col="{ span: 17, offset: 7 }">
            <a-button @click="resetForm">取消</a-button>
            <a-button type="primary" html-type="submit" style="margin-left: 50px"
              >确认</a-button
            >
          </a-form-item>
        </a-form>
      </a-modal>
      <!-- 修改策略 -->
      <a-modal
        v-model:visible="visible3"
        title="策略管理"
        :footer="null"
        @cancel="notOk"
      >
        <a-form
          name="custom-validation"
          ref="formRef"
          :model="formState3"
          :rules="rules"
          v-bind="layout"
          @finish="handleFinish3"
          @finishFailed="handleFinishFailed2"
        >
          <a-form-item label="设备策略" v-if="!formState2._id">
              <a-select v-model:value="formState3.strategyid" placeholder="请选择">
                  <a-select-option v-for="(i) in stralist" :key="i._id" :value="i._id">{{ i.name }}</a-select-option>
              </a-select>
          </a-form-item>
          <a-form-item v-else>
            <p>机械编号：{{ formState2._id }}</p>
            <p>策略名称：{{ formState2.name }}</p>
            <p>策略方案：{{ formState2.scheme }}%</p>
          </a-form-item>
          <a-form-item :wrapper-col="{ span: 17, offset: 7 }" v-if="!formState2._id">
            <a-button @click="resetForm">取消</a-button>
            <a-button type="primary" html-type="submit" style="margin-left: 50px"
              >确认</a-button
            >
          </a-form-item>
          <a-form-item :wrapper-col="{ span: 15, offset: 10 }" v-else>
            <a-button @click="handleFinish3">取消策略</a-button>
          </a-form-item>
        </a-form>
      </a-modal>
    </div>
  </template>
  <script setup>
  import { ref, reactive, toRefs, onMounted } from "vue";
  import {
    SmileOutlined,
    DownOutlined,
    SearchOutlined,
    PlusCircleOutlined,
    PlusOutlined, 
    LoadingOutlined,
  } from "@ant-design/icons-vue";
  import { Form, message } from "ant-design-vue";
  import {
    getequipmentTypes,
    getequipment,
    postequipment,
    delequipment,
    putequipment,
    setstraa,
    getstrategys,
    putequipmentstr
  } from "@/api/peng/equipment";
  import {
    GetCooperativeLists
  } from "@/api/tian/pt";
  
  // 头部输入
  let name = ref("");
  let ptid = ref("");
  // 表单添加
  const formRef = ref();
  const { formState,formState2,formState3 } = toRefs(
    reactive({
      formState: {
        state:'0',
        typeid:'',
        ptid:'',
        strategyid:''
      },
      formState2:{},
      formState3:{
        _id:'',
        strategyid:''
      },
    })
  );
  // 修改框控制
  const visible2 = ref(false);
  // 表格配置
  const columns = [
    {
      title: "序号",
      dataIndex: "_id",
      key: "_id",
    },
    {
      title: "设备编号",
      dataIndex: "_id",
      key: "_id",
    },
    {
      title: "设备型号",
      dataIndex: "typeid.name",
      key: "_id",
    },
    {
      title: "详细地址",
      dataIndex: "ptid.xidi",
      key: "_id",
    },
    {
      title: "合作商",
      dataIndex: "ptid.cooperative.name",
      key: "_id",
    },
    {
      title: "设备状态",
      key: "_id",
      slots: {
        customRender: "state",
      },
    },
    {
      title: "操作",
      key: "action",
      slots: {
        customRender: "action",
      },
    },
  ];
  // 表格内容数据
  let datas = ref([]);
  let typedata = ref([]);
  let pointslist = ref([])
  let stralist = ref([])
  // 添加控制区
  const visible = ref(false);
  const showModal = () => {
    visible.value = true;
  };
  const notOk = () => {
    resetForm();
  };
  // 添加表单控制区
  let validatetypeid = async (rule, value) => {
    if (value === "") {
      return Promise.reject("请选择型号");
    }
  };
  const rules = {
    typeid: [
      {
        required: true,
        validator: validatetypeid,
        trigger: "change",
      },
    ],
  };
  const layout = {
    labelCol: {
      span: 5,
    },
    wrapperCol: {
      span: 20,
    },
  };
  // 确定添加验证成功 添加数据
  const handleFinish = async (values) => {
    // console.log(values, formState.value);
    let { data } = await postequipment(formState.value);
    {
      data.code === 200 ? message.success("添加成功") : message.error("添加失败");
    }
    getdata();
    resetForm();
  };
  // 确定添加验证失败
  const handleFinishFailed = (errors) => {
    console.log("no");
  };
  // 重置关闭
  const resetForm = () => {
    formState.value={
        state:'0',
        typeid:'',
        ptid:'',
        strategyid:''
      }
      formState3.value={
        _id:'',
        strategyid:''
      }
    formRef.value.resetFields();
    visible.value = false;
    visible2.value = false;
  };
  // 获取数据
  const getstras = async ()=>{
    let {data} = await getstrategys()
    console.log(data);
    stralist.value=data.data
  }
  const getpoints = async ()=>{
    let { data } = await GetCooperativeLists();
    console.log(data);
    pointslist.value = data.data;
  }
  const getTypedata = async () => {
    let { data } = await getequipmentTypes();
    console.log(data);
    typedata.value = data.data;
  };
  const getdata = async () => {
    let { data } = await getequipment(name.value,page.value,pageSize.value);
    console.log(data);
    datas.value = data.data;
    total.value = data.count;
  };
  // 删除数据
  const deldata = async (id) => {
    let { data } = await delequipment(id);
    console.log(data);
    {
      data.code === 200 ? message.success("删除成功") : message.error("删除失败");
    }
    getdata();
  };
  // 修改数据控制区
  let _id = ref("");
  const put = (val) => {
    // console.log(val);
    _id.value = val._id;
    formState2.value = val;
    visible2.value = true;
    console.log(formState2.value);
  };
  const nono = (e)=>{
    ptid.value=e
    console.log(e);
  }
  // 确定修改验证成功 修改数据
  const handleFinish2 = async (values) => {
    console.log(values, formState2.value);
    let { data } = await putequipment({_id:_id.value,ptid:ptid.value});
    {
      data.code === 200 ? message.success("修改成功") : message.error("修改失败");
    }
    getdata();
    resetForm();
  };
  // 确定修改验证失败
  const handleFinishFailed2 = (errors) => {
    console.log("no");
  };
  // 确定修改验证成功 修改策略
  const handleFinish3 = async (values) => {
    console.log(values, formState2.value);
    let { data } = await putequipmentstr(formState3.value,backlist.value);
    {
      data.code === 200 ? message.success("修改成功") : message.error("修改失败");
    }
    getdata();
    formState2.value={}
    formState3.value={
        _id:'',
        strategyid:''
      },
      backlist.value=[]
    visible3.value=false
  };
//   批量操作
  const putlist = ()=>{
    console.log(backlist.value);
    if(!backlist.value[0]){
        message.error('请选中操作')
    }else{
      formState2.value={}
        visible3.value=true
    }
  }
  // 分页
   // 当前页
   let page = ref(1);
  // 每页条数
   let pageSize = ref(10);
   // 总数量
   let total = ref(0);
   // 上一页
   const onup = () => {
   page.value--;
   getdata()
   };
   // 下一页
   const ondown = () => {
   page.value++;
   getdata()
   };
//    全选反选
let backlist = ref([])
const rowSelection = {
      onChange: (selectedRowKeys, selectedRows) => {
        backlist.value=selectedRows
        console.log(backlist);
      },
      getCheckboxProps: record => ({
        disabled: record.name === 'Disabled User',
        // Column configuration not to be checked
        name: record.name,
      }),
    };
    // 策略修改
  let visible3 = ref(false)
  const setstra =async (val)=>{
    formState3.value._id=val._id
    if(val.strategyid===''){
      visible3.value=true
    }else{
      let {data} = await setstraa(val._id)
      console.log(data);
      formState2.value=data.datas
      visible3.value=true
    }
  }
  onMounted(() => {
    getdata();
    getTypedata()
    getpoints()
    getstras()
  });
  </script>
  
  <style scoped>
  .but1{
    background: linear-gradient(135deg,#ff9743,#ff5e20)!important;
    border:none;
    margin-bottom: 10px;
  }
  .but2{
    background-color: #fbf4f0!important;
    border: none;
    margin-bottom: 10px;
    margin-left: 10px;
    color: #655b56!important;
  }
  </style>